package com.app.signing.view.setting.signing

import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.text.TextUtils
import android.view.Menu
import android.view.MenuItem
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.amap.api.maps.AMap
import com.amap.api.maps.AMap.OnCameraChangeListener
import com.amap.api.maps.AMap.OnMapLoadedListener
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.BitmapDescriptorFactory
import com.amap.api.maps.model.CameraPosition
import com.amap.api.maps.model.Circle
import com.amap.api.maps.model.CircleOptions
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.Marker
import com.amap.api.maps.model.MarkerOptions
import com.app.signing.R
import com.app.signing.app.App
import com.app.signing.app.loge
import com.app.signing.app.logi
import com.app.signing.data.SpManager
import com.app.signing.data.bean.SigningSetting
import com.app.signing.view.base.BaseActivity
import com.app.signing.widget.SigningSettingDialog
import com.app.signing.widget.SigningSettingDialog.NoticeDialogListener
import kotlinx.android.synthetic.main.activity_signing_tool.bt_signing_detail
import kotlinx.android.synthetic.main.activity_signing_tool.map_tool
import kotlinx.android.synthetic.main.activity_signing_tool.text_signing_detail
import kotlinx.android.synthetic.main.activity_signing_tool.toolbar_signing_setting

class SigningToolActivity : BaseActivity(), OnCameraChangeListener, OnMapLoadedListener,
    AMapLocationListener, NoticeDialogListener {

    private lateinit var map: AMap
    private lateinit var locationClient: AMapLocationClient
    private var locationCircle: Circle? = null
    private var locationMarker: Marker? = null
    /**
     * 当前定位坐标
     */
    private var currentLatLng: LatLng? = null
    /**
     * 定位半径
     */
    private var radius: Double = 100.0

    private var isLocation: Boolean = true

    override fun getLayoutId(): Int {
        return R.layout.activity_signing_tool
    }

    override fun initData() {
        val (latitude, longitude, radius) = SpManager.INSTANCE.readSigningSetting()
        if (latitude == 0.0 || longitude == 0.0) {
            return
        }
        isLocation = false
        this.radius = radius
        currentLatLng = LatLng(latitude, longitude)
    }

    override fun initView(savedInstanceState: Bundle?) {
        setSupportActionBar(toolbar_signing_setting)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.setHomeAsUpIndicator(R.drawable.ic_arrow_back)
        map_tool.onCreate(savedInstanceState)
        init()
        initLocation()
        bt_signing_detail.setOnClickListener {
            currentLatLng?.let {
                // 保存定位结果
                SpManager.INSTANCE.saveSigningSetting(
                    SigningSetting(it.latitude, it.longitude, radius)
                )
                finish()
            }
        }
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.activity_signing_tool_menu, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        when (item?.itemId) {
            android.R.id.home -> {
                finish()
                return true
            }
            R.id.menu_signing_range -> {
                SigningSettingDialog.newInstance().show(supportFragmentManager, "signing")
            }
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onResume() {
        super.onResume()
        map_tool.onResume()
        if (isLocation) {
            startLocation()
        }
    }

    override fun onPause() {
        super.onPause()
        map_tool.onPause()
    }

    override fun onSaveInstanceState(outState: Bundle?) {
        super.onSaveInstanceState(outState)
        map_tool.onSaveInstanceState(outState)
    }

    override fun onDestroy() {
        super.onDestroy()
        map_tool.onDestroy()
        destroyLocation()
    }

    private fun init() {
        map = map_tool.map
        map.uiSettings.isZoomControlsEnabled = false
        map.setOnCameraChangeListener(this)
        map.setOnMapLoadedListener(this)
        if (!isLocation) {
            map.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLatLng, 16f))
        }
    }

    /**
     * 定位初始化
     */
    private fun initLocation() {
        locationClient = AMapLocationClient(App.app)
        locationClient.setLocationListener(this)
    }

    /**
     * 开始定位
     */
    private fun startLocation() {
        locationClient.setLocationOption(getLocationOptions())
        locationClient.startLocation()
        "开始定位".logi()
    }

    /**
     * 结束定位
     */
    private fun destroyLocation() {
        locationClient.onDestroy()
    }

    /**
     * 定位配置
     */
    private fun getLocationOptions(): AMapLocationClientOption {
        val option = AMapLocationClientOption()
        option.locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
        option.httpTimeOut = 30000
        option.isNeedAddress = true
        option.isLocationCacheEnable = false
        option.isOnceLocation = true
        return option
    }

    /**
     * 定位结果回调
     */
    override fun onLocationChanged(p0: AMapLocation?) {
        if (p0 == null || p0.errorCode != 0) {
            "定位失败,code--${p0?.errorCode}:${p0?.errorInfo}".loge()
            showToast("定位失败，code:${p0?.errorCode}")
            return
        }
        "定位成功".logi()
        val latLng = LatLng(p0.latitude, p0.longitude)
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16f))
    }

    /**
     * 地图加载完毕
     */
    override fun onMapLoaded() {
        "map camera loaded".logi()
        val latLng = map.cameraPosition.target
        addSigningMarker(latLng)
        drawSigningCircle(latLng)
        setSigningDetail(latLng)
    }

    override fun onCameraChange(p0: CameraPosition?) {
    }

    override fun onCameraChangeFinish(p0: CameraPosition?) {
        p0?.let {
            drawSigningCircle(it.target)
            setSigningDetail(it.target)
        }
    }

    override fun onDialogPositiveClick(
        dialog: DialogFragment?,
        value: String?
    ) {
        if (TextUtils.isEmpty(value)) {
            return
        }
        radius = value?.toDouble() ?: 100.0
        locationCircle?.let {
            it.radius = radius
        }
    }

    override fun onDialogNegativeClick(dialog: DialogFragment?) {
    }

    /**
     * 增加地位点
     */
    private fun addSigningMarker(latLng: LatLng) {
        val screenPosition = map.projection.toScreenLocation(latLng)
        locationMarker?.destroy()
        locationMarker = map.addMarker(
            MarkerOptions().anchor(0.5f, 0.5f).icon(
                BitmapDescriptorFactory.fromResource(R.drawable.purple_pin)
            )
        )
        locationMarker?.setPositionByPixels(screenPosition.x, screenPosition.y)
    }

    /**
     * 画定位范围
     */
    private fun drawSigningCircle(latLng: LatLng) {
        currentLatLng = latLng
        if (locationCircle == null) {
            locationCircle = map.addCircle(
                CircleOptions().center(latLng).radius(radius).strokeWidth(5f)
            )
        } else {
            locationCircle!!.center = latLng
        }
    }

    /**
     * 显示定位点经纬度和定位范围
     */
    private fun setSigningDetail(latLng: LatLng) {
        val text = "经度：${latLng.longitude}\n纬度：${latLng.latitude}\n半径：${radius}m"
        text_signing_detail.text = text
    }
}
